package com.idbk.chargestation.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.assist.ActivitySetting;
import com.idbk.chargestation.activity.pile.ActivityPointHistory;
import com.idbk.chargestation.activity.user.ActivityBindPhone;
import com.idbk.chargestation.activity.user.ActivityBuildPile;
import com.idbk.chargestation.activity.user.ActivityLogin;
import com.idbk.chargestation.activity.user.ActivityMyBooking;
import com.idbk.chargestation.activity.user.ActivityMyCar;
import com.idbk.chargestation.activity.user.ActivityMyComment;
import com.idbk.chargestation.activity.user.ActivityMyFavorite;
import com.idbk.chargestation.activity.user.ActivityMyMessage;
import com.idbk.chargestation.activity.user.ActivityMyWallet;
import com.idbk.chargestation.activity.user.ActivityUnbindPhone;
import com.idbk.chargestation.activity.user.ActivityUserInfor;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.api.ChargeStationURL;
import com.idbk.chargestation.app.MyVersion;
import com.idbk.chargestation.bean.JsonLogin;
import com.idbk.chargestation.bean.JsonUser;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.CheckUtil;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;
import com.squareup.picasso.Picasso;

import java.util.Locale;

/**
 * @author liu, liangzw, lupc
 */
public class FragmentPersonalInfo extends Fragment implements OnClickListener {

    private final static String TAG = "FragmentPersonalInfo";

    private Context mContext;

    private View mBaseView;

    private TextView tvUserName, tvSignature, tvBalance, tvCollections;
    private ImageView ivUserHeader;

    private ImageView mImageTipMessage, mImageTipBooking;

    private ImageView mImageCarCertification;

    private LinearLayout mLinearCertification, mLinearGather, mLinearLayout_get_pile, mLinearBind, mLinesrUnbind;

    private int userRole;
    private String mUsermobile;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mBaseView = inflater.inflate(R.layout.fragment_user, container, false);

        mContext = getActivity();

        setupView();

        return mBaseView;
    }

    private void setupView() {

        //初始化界面
        mBaseView.findViewById(R.id.layout_userinfo).setOnClickListener(this);
        tvUserName = (TextView) mBaseView.findViewById(R.id.fragmentuser_textview_username);
        tvSignature = (TextView) mBaseView.findViewById(R.id.fragmentuser_textview_Personalitysignature);
        tvBalance = (TextView) mBaseView.findViewById(R.id.fragmentuser_textview_balance);
        tvCollections = (TextView) mBaseView.findViewById(R.id.fragmentuser_textview_collections);
        ivUserHeader = (ImageView) mBaseView.findViewById(R.id.fragment_user_imageview_userimage);

        mLinearBind = (LinearLayout)  mBaseView.findViewById(R.id.layout_bind);
        mLinesrUnbind = (LinearLayout)  mBaseView.findViewById(R.id.layout_unbind);
        mLinearCertification = (LinearLayout)  mBaseView.findViewById(R.id.certification);
        mLinearGather = (LinearLayout)  mBaseView.findViewById(R.id.gather);
        mLinearLayout_get_pile = (LinearLayout)  mBaseView.findViewById(R.id.layout_get_pile);

        mBaseView.findViewById(R.id.mymessage).setOnClickListener(this);
        mBaseView.findViewById(R.id.layout_get_pile).setOnClickListener(this);

        mBaseView.findViewById(R.id.layout_setting).setOnClickListener(this);

        //注册按钮监听事件
        mBaseView.findViewById(R.id.mycollection).setOnClickListener(this);
        mBaseView.findViewById(R.id.mywallet).setOnClickListener(this);
        mBaseView.findViewById(R.id.mybooking).setOnClickListener(this);
        mBaseView.findViewById(R.id.mymessage).setOnClickListener(this);
        mBaseView.findViewById(R.id.mycomment).setOnClickListener(this);
        mBaseView.findViewById(R.id.certification).setOnClickListener(this);
        mBaseView.findViewById(R.id.gather).setOnClickListener(this);
        mBaseView.findViewById(R.id.layout_bind).setOnClickListener(this);
        mBaseView.findViewById(R.id.layout_unbind).setOnClickListener(this);

        mImageTipMessage = (ImageView) mBaseView.findViewById(R.id.imageview_tip_message);
        mImageTipBooking = (ImageView) mBaseView.findViewById(R.id.imageview_tip_booking);

        if (MyVersion.getVersion(mContext).equals(MyVersion.VERSION_ZNYD)) {
            mImageCarCertification = (ImageView) mBaseView.findViewById(R.id.imageview_flag_car_certification);
            mImageCarCertification.setOnClickListener(this);
        }
    }

    private void jumpToActivity(Class<?> cls) {
            Intent intent = new Intent(mContext, cls);
            startActivity(intent);

    }

    @Override
    public void onClick(View v) {
        //除了 设置界面，其他界面都需要登录才能进入
        if (v.getId() == R.id.layout_setting) {
            Intent intent = new Intent(mContext, ActivitySetting.class);
            startActivity(intent);
            return;
        }
        //检查登录状态
        AppContext appContext = AppContext.getInstance();
        if (!appContext.isLogin()) {
            //进入登录界面
            Intent intent = new Intent(getActivity(), ActivityLogin.class);
            startActivity(intent);
            return;
        }

        switch (v.getId()) {
            case R.id.layout_userinfo://用户信息
                Intent intent = new Intent(mContext, ActivityUserInfor.class);
                startActivityForResult(intent, Const.CODE_REQUEST_REGISTER);
                break;
            case R.id.mymessage://我的消息
                jumpToActivity(ActivityMyMessage.class);
                break;
            case R.id.mybooking://我的预订
                userRole = AppContext.getInstance().getUserRole();
                if (userRole == 2) {
                    Toast.makeText(mContext, R.string.activity_business_title,Toast.LENGTH_SHORT).show();
                }else {
                    jumpToActivity(ActivityMyBooking.class);
                }
                break;
            case R.id.mywallet://我的钱包
                jumpToActivity(ActivityMyWallet.class);
                break;
            case R.id.mycollection://我的收藏
                jumpToActivity(ActivityMyFavorite.class);
                break;
            case R.id.mycomment://我的评论
                jumpToActivity(ActivityMyComment.class);
                break;
            case R.id.imageview_flag_car_certification:
            case R.id.certification://车主认证
                jumpToActivity(ActivityMyCar.class);
                break;
            case R.id.gather://充电点采集
                jumpToActivity(ActivityPointHistory.class);
                break;
            case R.id.layout_get_pile://我要建桩
                jumpToActivity(ActivityBuildPile.class);
                break;
            case R.id.layout_setting://设置
                jumpToActivity(ActivitySetting.class);
                break;
            case R.id.layout_bind:
                bindPhone();
                break;
            case R.id.layout_unbind:
                unBindPhone();
                break;
            default:
                break;
        }
    }

    private void bindPhone(){
        userRole = AppContext.getInstance().getUserRole();
        if (userRole == 2 &&( mUsermobile == null || mUsermobile.equals(""))){
            Intent intent = new Intent(mContext,ActivityBindPhone.class);
            startActivityForResult(intent, Const.CODE_REQUEST_EDIT);
        }else if (userRole == 2 &&( mUsermobile != null && !mUsermobile.equals(""))){
            Toast.makeText(mContext, "企业号账户已绑定手机号", Toast.LENGTH_SHORT).show();
        }
    }

    private void unBindPhone(){

        userRole = AppContext.getInstance().getUserRole();
        if (userRole == 2 &&( mUsermobile == null || mUsermobile.equals(""))){
            Toast.makeText(mContext, "企业号账户尚未绑定手机号", Toast.LENGTH_SHORT).show();
        }else if (userRole == 2 &&( mUsermobile != null && !mUsermobile.equals(""))){
            Intent intent  = new Intent(mContext,ActivityUnbindPhone.class);
            startActivityForResult(intent, Const.CODE_REQUEST_EDIT);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //编辑相关
        if (requestCode == Const.CODE_REQUEST_EDIT && resultCode == Activity.RESULT_OK) {
            //重新获取数据
            onResume();
            return;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        AppContext appContext = AppContext.getInstance();
        if (appContext.isLogin()) {
            ChargeStationAPI.getUserInfo(mResponseFirst);
        } else {
            loginAndGetData();
        }
        updateStatus();

        userRole = AppContext.getInstance().getUserRole();
        if(userRole == 2){
            mLinearCertification.setVisibility(View.GONE);
            mLinearGather.setVisibility(View.GONE);
            mLinearLayout_get_pile.setVisibility(View.GONE);
            mLinearBind.setVisibility(View.VISIBLE);
            mLinesrUnbind.setVisibility(View.VISIBLE);
        }else {
            mLinearCertification.setVisibility(View.VISIBLE);
            mLinearGather.setVisibility(View.VISIBLE);
            mLinearLayout_get_pile.setVisibility(View.VISIBLE);
            mLinearBind.setVisibility(View.GONE);
            mLinesrUnbind.setVisibility(View.GONE);
        }
    }

    private void loginAndGetData() {
        AppContext ac = AppContext.getInstance();
        String username = ac.getLoginUserName();
        String password = ac.getLoginPassword();
        if (username != null && password != null) {
            ChargeStationAPI.login(
                    username,
                    password,
                    ac.getPushClientId(),
                    ac.getUserRole(),
                    mResponseLogin);
        } else {
            clearData();
            ac.clearLoginState();
        }
    }

    private final EHttpResponse mResponseFirst = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonUser result = GsonUtils.toBean(JsonUser.class, response);
            if (result == null) {
                clearData();
            } else if (result.status == GlobalResult.OK.getStatus()) {
                bindView(result);
                mUsermobile = result.mobile;
            } else if (result.status == GlobalResult.TOKEN_INVALID.getStatus()
                    || result.status == GlobalResult.TOKEN_REQUIRED.getStatus()) {
                loginAndGetData();
            } else {
                //标准异常返回
                Toast.makeText(
                        mContext,
                        result.message,
                        Toast.LENGTH_SHORT)
                        .show();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            //打印调试信息
            Log.e(TAG, error.getMessage(), error.getCause());
        }

    };

    private final EHttpResponse mResponseLast = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonUser result = GsonUtils.toBean(JsonUser.class, response);
            if (result == null || result.status != GlobalResult.OK.getStatus()) {
                clearData();
                AppContext.getInstance().clearLoginState();
            } else {
                bindView(result);
                mUsermobile = result.mobile;
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            //打印调试信息
            Log.e(TAG, error.getMessage(), error.getCause());
            clearData();
            AppContext.getInstance().clearLoginState();
        }

    };

    private final EHttpResponse mResponseLogin = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonLogin result = GsonUtils.toBean(JsonLogin.class, response);
            if (result == null) {
                return;
            }

            if (result.status == GlobalResult.OK.getStatus()) {
                //记录登录信息
                AppContext ac = AppContext.getInstance();
                AppContext.getInstance().saveUserInfo(
                        result.token,
                        ac.getLoginUserName(),
                        ac.getLoginPassword(),
                        result.outTime);
                ChargeStationAPI.getUserInfo(mResponseLast);
            } else {
                clearData();
                AppContext.getInstance().clearLoginState();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            //打印调试信息
            Log.e(TAG, error.getMessage(), error.getCause());
            //消息提示
            clearData();
            AppContext.getInstance().clearLoginState();
        }

    };

    private void bindView(JsonUser result) {
        AppContext.getInstance().setUserInfo(result.userId, result.realName);

        tvUserName.setText(result.realName);

        AppContext.getInstance().setCertification(result.ownerStatus);//设置车主认证标志
        if (MyVersion.getVersion(mContext).equals(MyVersion.VERSION_ZNYD)) {
            if (result.isCertified) {
                mImageCarCertification.setVisibility(View.VISIBLE);
                mImageCarCertification.setImageResource(R.drawable.ico_me_verify_car_owner_active);
            } else {
                mImageCarCertification.setVisibility(View.VISIBLE);
                mImageCarCertification.setImageResource(R.drawable.ico_me_verify_car_owner_normal);
            }
        }
        String balance = String.format(Locale.CHINA,
                "剩余金额：￥<font color='#23B7A1'>%s</font>",
                result.balance);
        tvBalance.setText(CheckUtil.textFromHtml(balance));
        if (result.bespeak == 0) {
            mImageTipBooking.setVisibility(View.INVISIBLE);
        } else {
            mImageTipBooking.setVisibility(View.VISIBLE);
        }

        String collections = String.format(Locale.CHINA,
                "已收藏： <font color='#df5a49'>%d</font>",
                result.collection4Points);
        tvCollections.setText(CheckUtil.textFromHtml(collections));

        if (result.signature == null || "".equals(result.signature) || result.signature.length() < 1) {
            tvSignature.setText("我很懒，什么都没写");
        } else {
            tvSignature.setText(result.signature);
        }

        String url = ChargeStationURL.getRootURL() + result.imageURL;
        Picasso.with(mContext)
                .load(url)
                .placeholder(R.drawable.ico_me_default_user_pic)
                .error(R.drawable.ico_me_default_user_pic)
                .into(ivUserHeader);
    }

    private void clearData() {
        ivUserHeader.setImageResource(R.drawable.ico_me_default_user_pic);
        tvUserName.setText("未登陆");
        tvBalance.setText("");
        tvCollections.setText("");
        tvSignature.setText(R.string.fragmentuser_textview_Personalitysignature);

        mImageTipBooking.setVisibility(View.INVISIBLE);
        if (MyVersion.getVersion(mContext).equals(MyVersion.VERSION_ZNYD)) {
            mImageCarCertification.setVisibility(View.INVISIBLE);
        }

    }

    private void updateStatus() {
        AppContext ac = AppContext.getInstance();
        if (!ac.isLogin()) {
            mImageTipMessage.setVisibility(View.GONE);
            return;
        }
        if (ac.isHasUnreadMessage()) {
            mImageTipMessage.setVisibility(View.VISIBLE);
        } else {
            mImageTipMessage.setVisibility(View.GONE);
        }
    }


}
